#include "bsp/bsp.h"
#include "adc.h"
#include "tim.h"
#include "gpio.h"
#include "version.h"


void SystemClock_Config(void)
{

  	RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  	RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  	/** Configure the main internal regulator output voltage
  	*/
  	HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST);

  	/** Initializes the RCC Oscillators according to the specified parameters
  	* in the RCC_OscInitTypeDef structure.
  	*/
  	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  	RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  	RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  	RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  	RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV2;
  	RCC_OscInitStruct.PLL.PLLN = 85;
  	RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV8;
  	RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  	RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  	if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  	{
    	//Error_Handler();
  	}

  	/** Initializes the CPU, AHB and APB buses clocks
  	*/
  	RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  	RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  	RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  	RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  	RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

  	if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  	{
    	//Error_Handler();
  	}

    /**Configure the Systick interrupt time 
    */
  	HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);

    /**Configure the Systick 
    */
  	HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);

  	/* SysTick_IRQn interrupt configuration */
  	HAL_NVIC_SetPriority(SysTick_IRQn, SYSTICK_IRQ_PRIOTIRY, 0);
}

void HAL_MspInit(void)
{
	__HAL_RCC_SYSCFG_CLK_ENABLE();
  	__HAL_RCC_PWR_CLK_ENABLE();

	HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
	/* SysTick_IRQn interrupt configuration */
	HAL_NVIC_SetPriority(SysTick_IRQn, SYSTICK_IRQ_PRIOTIRY, 0);

	HAL_PWREx_DisableUCPDDeadBattery();
}

void MX_DMA_Init(void) 
{
	/* DMA controller clock enable */
	__HAL_RCC_DMA1_CLK_ENABLE();
	__HAL_RCC_DMA2_CLK_ENABLE();
	__HAL_RCC_DMAMUX1_CLK_ENABLE();
}

void MX_IWDG_Init(void)
{
#if (CONFIG_DEBUG==0)
	IWDG_HandleTypeDef hiwdg;
	//wdog clk is 32k, 2s timeout
  	hiwdg.Instance = IWDG;
 	hiwdg.Init.Prescaler = IWDG_PRESCALER_16;
  	hiwdg.Init.Reload = 4095;
	hiwdg.Init.Window = 4095;
	HAL_IWDG_Init(&hiwdg);
#endif
}

void wdog_reload(void) {
#if (CONFIG_DEBUG==0)
	IWDG_HandleTypeDef hiwdg;
	hiwdg.Instance = IWDG;
	HAL_IWDG_Refresh(&hiwdg);
#endif
}

u8 mcu_chip_id(u8 *buff)
{
	u32 values[] = { REG32(0x1FFF7590), REG32(0x1FFF7594), REG32(0x1FFF7598)};
	memcpy(buff, values, sizeof(values));
	return sizeof(values);
}

